<template>
  <div class="quizz">
    <header>
      <div class="btn primary" v-if="now !== 1" @click="beforeQuestion">上一道题</div>
      <div class="time">剩余时间：{{ time }}</div>
      <div class="btn primary" v-if="ques[ques.length - 1].id === que.id" @click="save">保存</div>
      <div class="btn primary" @click="nextQuestion" v-else>下一道题</div>
    </header>
    <main>
      <div class="que">
        <p>第{{ now }}题<span class="desc">{{ getType() }}</span></p>
        <p class="title">{{ que.name }}</p>
        <div class="ans-container" v-if="que.queType !== '2'">
          <div
            class="ans"
            :class="{ chosen: chosen.includes('A') }"
            @click="choose('A')">A. {{que.answerA}}</div>
          <div
            class="ans"
            :class="{ chosen: chosen.includes('B') }"
            @click="choose('B')">B. {{que.answerB}}</div>
          <div
            class="ans"
            :class="{ chosen: chosen.includes('C') }"
            @click="choose('C')">C. {{que.answerC}}</div>
          <div
            class="ans"
            :class="{ chosen: chosen.includes('D') }"
            @click="choose('D')">D. {{que.answerD}}</div>
        </div>
        <div class="ans-container" v-else>
          <div
            class="ans"
            :class="{ chosen: chosen }"
            @click="choose(true)">正确</div>
          <div
            class="ans"
            :class="{ chosen: !chosen }"
            @click="choose(false)">错误</div>
        </div>
      </div>
    </main>
  </div>
</template>
<script>
import api from '@/api/quizz';

export default {
  name: 'Quizz',
  data() {
    return {
      com: '',
      commentNum: 0,
      now: 1,
      chosen: [],
      time: null,
      // 你后面改成ques.length * 60 * 2
      seconds: -1,
      que: {
        id: 'que3',
        name: '这道题怎么做？',
        queType: 0,
        ans: null,
      },
      canLeave: false,
      ques: [
        {
          id: 'que1',
          name: '这道题怎么做？',
          queType: 0,
          ans: null,
        },
        {
          id: 'que2',
          name: '这道题怎么做？',
          queType: 1,
          ans: null,
        },
        {
          id: 'que3',
          name: '这道题怎么做？',
          queType: 2,
          ans: null,
        },
      ],
      comments: [],
      answers: [],
    };
  },
  methods: {
    choose(ans) {
      if (this.que.queType !== '2') {
        if (this.que.queType === '0') {
          this.chosen = [ans];
          this.answers[this.now - 1].ans = [ans];
        } else {
          // eslint-disable-next-line no-unused-expressions
          this.chosen.includes(ans)
            ? this.chosen.splice(this.chosen.findIndex(e => e === ans), 1)
            : this.chosen.push(ans);
          this.answers[this.now - 1].ans = this.chosen;
        }
      } else {
        this.chosen = ans;
        this.answers[this.now - 1].ans = ans;
      }
    },
    addComment() {
      const params = new URLSearchParams();
      params.append('questionId', this.que.id);
      params.append('userId', sessionStorage.getItem('userId'));
      params.append('description', this.com);
      api.addByUserId(params).then(async (response) => {
        if (response.data.code === 200) {
          this.$alert('添加成功');
          this.com = '';
          this.getComment();
        } else {
          this.$alert(response.data.message);
        }
      });
    },
    nextQuestion() {
      this.now += 1;
      this.chosen = this.answers[this.now - 1].ans;
      this.que = this.ques[this.now - 1];
      this.getComment();
    },
    beforeQuestion() {
      this.now -= 1;
      this.chosen = this.answers[this.now - 1].ans;
      this.que = this.ques[this.now - 1];
      this.getComment();
    },
    getType() {
      if (this.que.queType === '0') {
        return '单选题';
      } else if (this.que.queType === '1') {
        return '多选题';
      }
      return '判断题';
    },
    save() {
      const finAnswer = [];
      for (let i = 0; i < this.answers.length; i += 1) {
        if (this.ques[i].queType === '0') {
          finAnswer.push({
            questionId: this.answers[i].questionId,
            chosenAnswer: this.answers[i].ans.length !== 0 ? this.answers[i].ans[0] : '',
          });
        }
        if (this.ques[i].queType === '1') {
          const a = this.answers[i].ans.join(',');
          finAnswer.push({
            questionId: this.answers[i].questionId,
            chosenAnswer: a,
          });
        }
        if (this.ques[i].queType === '2') {
          let a = '';
          if (this.answers[i].ans !== null) {
            if (this.answers[i].ans === true) {
              a = '0';
            } else {
              a = '1';
            }
          }
          finAnswer.push({
            questionId: this.answers[i].questionId,
            chosenAnswer: a,
          });
        }
      }
      // eslint-disable-next-line no-console
      console.log(this.$route.query.type === 'random');
      if (this.$route.query.type === 'random') {
        const params = new URLSearchParams();
        params.append('businessId', this.$route.query.paperId);
        params.append('answer', JSON.stringify(finAnswer));
        api.updateSelf(params).then(async (response) => {
          if (response.data.code === 200) {
            this.$alert('考试结束');
          } else {
            this.$alert(response.data.message);
          }
        });
      } else {
        const params = new URLSearchParams();
        params.append('businessId', this.$route.query.paperId);
        params.append('userId', sessionStorage.getItem('userId'));
        params.append('examId', this.$route.query.examId);
        params.append('answer', JSON.stringify(finAnswer));
        api.update(params).then(async (response) => {
          if (response.data.code === 200) {
            this.$alert('考试结束');
          } else {
            this.$alert(response.data.message);
          }
        });
      }

      this.canLeave = true;
      // FIXME: 改成写完试卷就查看结果
      this.$router.go(-1);
    },
    getComment() {
      const params = new URLSearchParams();
      params.append('questionId', this.que.id);
      api.getComment(params).then(async (response) => {
        const datas = response.data.data;
        this.commentNum = datas.length;
        this.comments = [];
        for (let i = 0; i < datas.length; i += 1) {
          this.comments.push({
            id: datas[i].businessId,
            user: datas[i].username,
            desc: datas[i].description,
            createDate: datas[i].createDate,
          });
        }
      });
    },
    async getPaper() {
      const res = await api.detail(this.$route.query.paperId);
      const datas = res.data.data.bquestionList;
      this.ques = [];
      for (let i = 0; i < datas.length; i += 1) {
        this.ques.push({
          id: datas[i].businessId,
          name: datas[i].title,
          queType: datas[i].type,
          answerA: datas[i].boptionList ? datas[i].boptionList[0].optionContent : '选项A',
          answerB: datas[i].boptionList ? datas[i].boptionList[1].optionContent : '选项B',
          answerC: datas[i].boptionList ? datas[i].boptionList[2].optionContent : '选项C',
          answerD: datas[i].boptionList ? datas[i].boptionList[3].optionContent : '选项D',
          ans: null,
        });
        if (datas[i].type !== 2) {
          this.answers.push({
            questionId: datas[i].businessId,
            ans: [],
          });
        } else {
          this.answers.push({
            questionId: datas[i].businessId,
            ans: null,
          });
        }
      }
      if (this.ques.length !== 0) {
        this.que = this.ques[0];
        this.chosen = this.answers[0].ans;
        this.getComment();
      }
      this.seconds = this.ques.length * 60 * 2;
    },
  },
  created() {
    this.$emit('exam', true);
  },
  mounted() {
    // eslint-disable-next-line no-unused-expressions
    // this.que.queType === 2 ? this.chosen = null : this.chosen = [];
    const that = this;
    this.getPaper().then((res) => {
      const interval = setInterval(() => {
        that.seconds -= 1;
        let min = parseInt(that.seconds / 60, 10);
        let sec = that.seconds - (min * 60);
        if (sec < 10) {
          sec = `0${sec}`;
        }
        if (min < 10) {
          min = `0${min}`;
        }
        that.time = `${min}:${sec}`;
        if (that.seconds === 0) {
          clearInterval(interval);
          // TODO 考试结束逻辑
          const finAnswer = [];
          for (let i = 0; i < this.answers.length; i += 1) {
            if (this.ques[i].queType === '0') {
              finAnswer.push({
                questionId: this.answers[i].questionId,
                chosenAnswer: this.answers[i].ans.length !== 0 ? this.answers[i].ans[0] : '',
              });
            }
            if (this.ques[i].queType === '1') {
              const a = this.answers[i].ans.join(',');
              finAnswer.push({
                questionId: this.answers[i].questionId,
                chosenAnswer: a,
              });
            }
            if (this.ques[i].queType === '2') {
              let a = '';
              if (this.answers[i].ans !== null) {
                if (this.answers[i].ans === true) {
                  a = '0';
                } else {
                  a = '1';
                }
              }
              finAnswer.push({
                questionId: this.answers[i].questionId,
                chosenAnswer: a,
              });
            }
          }
          // TODO: 保存试卷
          if (this.$route.query.type === 'random') {
            const params = new URLSearchParams();
            params.append('businessId', this.$route.query.paperId);
            params.append('answer', JSON.stringify(finAnswer));
            api.updateSelf(params).then(async (response) => {
              if (response.data.code === 200) {
                this.$alert('考试结束');
              } else {
                this.$alert(response.data.message);
              }
            });
          } else {
            const params = new URLSearchParams();
            params.append('userId', sessionStorage.getItem('userId'));
            params.append('examId', this.$route.query.examId);
            params.append('answer', JSON.stringify(finAnswer));
            api.update(params).then(async (response) => {
              if (response.data.code === 200) {
                this.$alert('考试结束');
              } else {
                this.$alert(response.data.message);
              }
            });
          }
        }
      }, 1000);
    });
  },
  beforeRouteLeave(to, from, next) {
    // 考试结束前禁止离开
    if (!this.seconds > 0 || this.canLeave) {
      this.$emit('exam', false);
      next();
    }
    next(false);
  },
};
</script>
<style lang="less">
@import url(../../../../static/style/site.vars.less);
.quizz {
  width: 1200px;
  margin: 0 auto;
  &>header {
    display: flex;
    margin: 20px 0;
    .time {
      flex:1;
      text-align:center;
      padding-top: 8px;
    }
  }
  &>main {
    .que {
      box-sizing: border-box;
      padding: 30px 40px;
      background: rgba(85, 92, 98, 0.05);
      &>p {
        margin-bottom: 10px;
        &.title {
          font-size: 25px;
          margin-bottom: 15px;
        }
      }
      .ans-container {
        .ans {
          box-sizing: border-box;
          padding: 10px 15px;
          margin-bottom: 10px;
          background: #fff;
          border: 1px solid rgb(107, 97, 97);
          cursor: pointer;
          user-select: none;
          &.chosen {
            color: rgb(23, 116, 223);
            border-color: rgb(78, 138, 207);
            box-shadow: 0 0 2px rgb(78, 138, 207);
          }
        }
      }
    }
    .comment {
      margin-bottom: 80px;
      &>header {
        padding: 20px 0;
        border-bottom: 1px solid rgba(190, 190, 190, 0.356);
      }
      &>main {
        .input {
          margin-top: 10px;
          text-align: right;
          display: flex;
          &>img {
            border-radius: 46px;
            margin-right: 20px;
          }
          &>textarea {
            width: 100%;
            height: 88px;
          }
        }
        .row {
          margin: 10px 0;
          display: flex;
          &>img {
            border-radius: 46px;
            margin-right: 20px;
          }
          .text-content {
            background: rgb(255, 255, 255);
            width: 100%;
            padding: 20px;
            .name {
              color: @site-main;
              margin-bottom: 10px;

            }
          }
        }
      }
    }
    .desc {
      color: rgb(172, 172, 172);
      margin-left: 20px;
      font-size: 12px;
    }
  }
}
</style>
